var _ = require("../lib/underscore")._,
	http = require("http"),
	sys = require("sys"),
	disk = require("./disk");

var Httpd = {};

exports.createHttpd = function (config) {
	var httpd = _.beget(Httpd);
	config = config ? config : {};
	httpd.port = config.port || 8080;
	httpd.host = config.host || null;;
	httpd.title = config.title || "HTTPD";
	httpd.version = config.version || 1.0;
	httpd.disk = config.disk || disk.createDisk();

	httpd.server = http.createServer(function (request, response) {
		// sys.log(sys.inspect(request));
		// sys.log(sys.inspect(response));
		httpd.disk.get(request, response, function (msg) {
			var header = {
				"Date": (new Date).toUTCString(),
				"Server": httpd.title + "/" + httpd.version + 
					 " (Node/" + process.platform + ")"
			};
			// TODO Fix header
			response.writeHead(msg.code, _.extend(msg.header, header));		
			response.end(msg.body);
		});
	});
	httpd.server.listen(httpd.port, httpd.host);
	sys.log("Server running at http://" + httpd.host + ":" + httpd.port);
	sys.log("PID: " + process.pid);
	return httpd;
};
